/**
 * Created by xiaolinzhang on 2016/11/1.
 */


var logger = require('../libs/log').logger;
var async = require('async');
var commService = require('../services/commService');
var wxService = require('../services/wxServices');
var wechat = require('../libs/wechat.js');
var upyun = require('../libs/upyun/utils');
var tjs = require('../libs/t');
var acc = require('../libs/acc');
var config = require('../conf/config.js');
var wxConfig = config['wechat'];
var wxCustConfig = config['wechatCust'];


exports.login = function (req,res,next) {


    // async.series([
    //     function (callback) {
    //         wxService.sessionGet(req,callback);
    //     }
    // ],function (err,result) {
    //     if(err){
    //         logger.error(err);
    //     }else {
    //         logger.debug(result);
    //     }
    // })


    var retUrl = req.query.retUrl||req.session.retUrl||'/rest/wx/operorder';
    if(req.query.retUrl){
        req.session.retUrl = req.query.retUrl;
    }



    // if(!req.session.openid){
    //     var wxurl = wxConfig.auth_url.replace('(appid)',wxConfig.appid)
    //         .replace('(redirect_uri)',config['murl']+'/rest/wx/wxauth')
    //         .replace('(scope)', 'snsapi_userinfo')
    //         .replace('(state)','login');
    //     return res.redirect(wxurl);
    // }

    // logger.debug(JSON.stringify(req.session.id));

    async.waterfall([
        function (callback) {
            var data={open_id:req.session.openid};
            wxService.getUserInfo(data,callback);
        },
        function (res,callback) {

            var rtnUser = JSON.parse(res);
            logger.debug("user:"+rtnUser);
            if(rtnUser.length>0 && rtnUser[0].state==1 && rtnUser[0].cstate==1 && rtnUser[0].realname != null){
                req.session.acc_name=rtnUser[0].name;
                req.session.channel_name=rtnUser[0].channel_name;
                req.session.org_id=rtnUser[0].org_id;
                req.session.channel_id=rtnUser[0].channel_id;
                req.session.emp_id = rtnUser[0].emp_id;
                req.session.retUrl = null;
                req.session.realname = rtnUser[0].realname;
                req.session.acctype = rtnUser[0].pay_method;
                logger.debug("session:"+JSON.stringify(req.session));
                commService.sessionSet(req,callback);
            }else {
                var token = acc.randomString(18);
                req.session.csrfToken = token;
                callback({code:1,token:token},null);
            }

        }
    ],function (err,result) {
        if(err){
            logger.error(err);
            if (err.code == 1){
                res.render('wx/login', {'title': '登录', 'token': err.token, 'retUrl':retUrl});
            }
        }else {
            return res.redirect(retUrl);
        }
    });
}

exports.wxauth = function(req,res,next) {
    var code = req.query.code;
    var state = req.query.state;
    var stateMap = {'login':'/rest/wx/login'};

    if(!code){
        logger.error('微信认证失败');
        res.status(200).end('微信认证失败');
        return;
    }

    async.waterfall([
        function (callback) {
            wechat.authCode(code,'1',callback);
        },
        function (res,callback) {
            logger.debug("ret:"+res)
            if(!res || !res.openid){
                logger.error('微信认证失败: wx authcode 失败');
                callback(200,null)
            }
            var openid = res.openid;
            var accessToken = res.access_token;
            req.session.openid = openid;
            wechat.getUserInfo(accessToken, openid,callback);
        },
        function (userinfo,callback) {
            if(!userinfo){
                logger.error('微信认证失败: 获取userinfo失败');
                callback(200,null);
            }

            req.session.wxnickname = userinfo.nickname;
            req.session.avatar = userinfo.headimgurl;
            logger.debug(JSON.stringify(req.session));
            callback(null,1);
        }
    ],function (err,result) {
        logger.debug("err:"+err+"============result:",result);
        if(err){
            logger.error(err)
            res.status(200).end('微信认证失败');
        }else {
            res.redirect(stateMap[state]);
            logger.debug("asdabasasdad");
        }
    });
}

exports.operorder = function (req,res,next) {

    async.parallel({
        prod:function (callback) {
            var data = {
                org_id:req.session.org_id
            };
            wxService.getProd(data,callback);
        },
        upyun:function (callback) {
            var bucket = config['upyun']['bucket'];
            var secret = config['upyun']['secret'];
            var cdnDomain = config['upyun']['domain'];
            var opts = {
                'bucket': bucket,
                'save-key' : config['upyun']['save-key'],//'/appimg/upload/{year}{mon}{day}/{filemd5}{.suffix}',
                'allow-file-type' : config['upyun']['allow-file-type'],//'bmp,png,jpeg,jpg,gif,mp4',
                'content-length-range' : config['upyun']['content-length-range'],//'1,20480000',//20MB
                'expiration': Math.round(new Date().getTime() / 1000) + 3600
            };

            var policy = upyun.Base64.encode(JSON.stringify(opts));
            var signature = upyun.md5sum(policy + '&' + secret);

            var upyum = {bucket: bucket,policy:policy,signature:signature,domain:cdnDomain};

            callback(null,upyum);
        },
        orderno:function (callback) {
            var otno = req.query.otno||'';
            var oprod = null;

            if(otno) {
                var data={org_id:req.session.org_id,out_trade_no:otno};
                var tmpProd = wxService.getOutTradeNo(data,callback);
                if (typeof tmpProd !== 'string' && tmpProd.length>0) {
                    oprod = tmpProd[0];
                }else{
                    otno='';
                }
            }
            var res = {otno:otno,oprod:oprod};
            callback(null,res);
        },
        annlist:function (callback) {
            wxService.getAnn(null,callback);
        }
    },function (err,result) {
        if(err){
            logger.debug("err:"+err);
            res.status("500").end(err);
        }else {
            logger.debug(JSON.stringify(result));
            res.render('wx/operorder', {
                'title': req.session.channel_name,
                'channel_name':req.session.channel_name,
                'org_id':req.session.org_id,
                'acc_name':req.session.acc_name,
                'channel_id':req.session.channel_id,
                'accType':req.session.acctype,
                'out_trade_no_old':result.orderno.otno,
                'oprod':result.orderno.oprod,
                'prod_list':JSON.parse(result.prod),
                'annlist':JSON.parse(result.annlist),
                'upyun':result.upyun
            });
        }
    });
}


exports.cardList = function (req,res,next) {
    var now = new Date();
    var tmd = new Date();
    tmd.setDate(tmd.getDate()+1);
    logger.debug(req.session.acc_name);
    res.render('wx/cardList', {
        'title': '销售记录',
        'channel_name':req.session.channel_name,
        'org_id':req.session.org_id,
        'acc_name':req.session.acc_name,
        'channel_id':req.session.channel_id,
        'sdate':tjs.dateformat('yyyy-MM-dd', now),
        'edate':tjs.dateformat('yyyy-MM-dd', tmd)
    });
}

exports.getCardRecord = function (req,res,next) {
    async.series([
        function (callback) {
            if(req.body.name!=req.session.acc_name)
            {
                callback(JSON.stringify({'res':-1,'info':'账户不相同'}),null);
            } else if(req.body.channel_id!=req.session.channel_id){
                callback(JSON.stringify({'res':-1,'info':'渠道号不相同'}),null);
            } else {
                req.body.emp_id = req.session.emp_id;
                wxService.getCardRecord(req,callback);
            }
        }
    ],function (err,result) {
        if(err){
            res.send(err);
        }else {
            res.send({'res':1,'info':JSON.parse(result)});
        }
    })
}

exports.usercenter = function (req,res,next) {
    async.series({
        empordsum:function (callback) {
            var data={
                emp_id:req.session.emp_id
            }
            wxService.getEmpOrdSum(data,callback);
        },
        emprank:function (callback) {
            var data={
                channel_id:req.session.channel_id,
                emp_id:req.session.emp_id
            }
            wxService.getEmpRank(data,callback);
        }
    },function(err,result){
            if(err){
                logger.error(err);
            }else {
                var cc = 0;
                var fee = 0;
                res.render('wx/usercenter', {
                    'title': '用户中心',
                    'channel_name':req.session.channel_name,
                    'org_id':req.session.org_id,
                    'acc_name':req.session.acc_name,
                    'channel_id':req.session.channel_id,
                    'avatar':req.session.avatar,
                    'cnt':cc,
                    'rank':result.emprank.pm,
                    'fee':(fee/100).toFixed(2)
                });
            }
        });
}